<template>
    <!-- wrapper start -->
    <div class="wrapper no-user-select">
        <!-- register form start -->
        <form class="form">
            <div class="form-items">
                <label for="username" class="label">用户名（1-8位汉字）</label>
                <div class="w-full flex align-center">
                    <input type="text" name="username" id="username" v-model="form.username" @blur="validateUsername" />
                    <div id="username_status" class="status"></div>
                </div>
            </div>
            <div class="form-items">
                <label for="password" class="label">密码(6-16位字母+数字复杂组合)</label>
                <div class="w-full flex align-center">
                    <input type="password" name="password" id="password" v-model="form.password" @blur="validatePassword" />
                    <div id="password_status" class="status"></div>
                </div>
            </div>
            <div class="form-items">
                <label for="email" class="label">
                    邮箱
                    <span v-if="errorEmail" class="text-red-500 error">（不可用的邮箱）</span>
                </label>
                <div class="w-full flex align-center">
                    <input type="email" name="email" id="email" v-model="form.email" @blur="validateEmail" />
                    <!-- 邮箱未发送验证码 -->
                    <div v-show="errorEmailFormat" class="status error">❌</div>
                    <div v-show="sendEmailBtn" id="email_status2" class="status email-send-text" @click="sendEmailEvent">发送验证</div>
                    <!-- 邮箱已发送验证码 -->
                    <Countdown v-if="sendEmail" class="status" :number="60" :ms="1000" />
                </div>
            </div>
            <div class="email-auth">
                <input placeholder="" type="tel" maxlength="1" v-model="form.authCode[0]" />
                <input placeholder="" type="tel" maxlength="1" v-model="form.authCode[1]" />
                <input placeholder="" type="tel" maxlength="1" v-model="form.authCode[2]" />
                <input placeholder="" type="tel" maxlength="1" v-model="form.authCode[3]" />
            </div>
            <div class="submit" @click="registerEvent">注册</div>
            <span class="span">
                已经拥有账户?
                <a href="javascript:;" @click="goToLoginEvent">前往登录</a>
            </span>
        </form>
        <!-- register form end -->
    </div>
    <!-- wrapper end -->
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { sendEmailAuthCode } from '@api/email';

/* ***********************************通用属性*********************************** */
const router = useRouter();
const useUser = useUserStore();

/* ***********************************表单属性*********************************** */
// 错误的email格式状态
const errorEmailFormat = ref(false);
// 不可使用的email状态
const errorEmail = ref(false);
// 邮箱发送验证码按钮
const sendEmailBtn = ref(false);
// 发送验证码倒计时
const sendEmail = ref(false);
// 表单数据
const form = reactive({
    username: '',
    password: '',
    email: '',
    authCode: ['', '', '', ''],
});

/* ***********************************验证表单*********************************** */
// 验证用户名格式(1-8位汉子)
const validateUsername = () => {
    const reg = new RegExp('^[\u4e00-\u9fa5]{1,8}$');
    if (!reg.test(form.username)) {
        document.getElementById('username_status')!.innerText = '❌';
        document.getElementById('username_status')!.classList.add('error');
        return false;
    } else {
        document.getElementById('username_status')!.innerText = '✔';
        document.getElementById('username_status')!.classList.remove('error');
        return true;
    }
};
// 验证密码格式(6-16位)
const validatePassword = () => {
    const reg = new RegExp(/^(?=.*[0-9])(?=.*[a-zA-Z])(?!.*([0-9])\1{2})(?!.*([a-zA-Z])\2{2})[0-9a-zA-Z]{6,16}$/);
    if (!reg.test(form.password)) {
        document.getElementById('password_status')!.innerText = '❌';
        document.getElementById('password_status')!.classList.add('error');
        return false;
    } else {
        document.getElementById('password_status')!.innerText = '✔';
        document.getElementById('password_status')!.classList.remove('error');
        return true;
    }
};
// 验证邮箱格式 635182455@qq.com 1803585958@qq.com
const validateEmail = async () => {
    return new Promise((resolve, _reject) => {
        sendEmail.value = false;
        sendEmailBtn.value = false;
        const reg = new RegExp(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/);
        if (!reg.test(form.email)) {
            // 邮箱格式错误
            errorEmailFormat.value = true;
            resolve(false);
        } else {
            // 邮箱格式正确
            errorEmailFormat.value = false;
            errorEmail.value = false;
            sendEmailBtn.value = true;
        }
    });
};
// 发送邮箱验证码 635182455@qq.com 1803585958@qq.com
const sendEmailEvent = async () => {
    sendEmailBtn.value = false;
    sendEmail.value = true;
    sendEmailAuthCode(form.email)
        .then((res) => {
            // 60s倒计时
            const timer = setTimeout(() => {
                if (sendEmail.value) {
                    sendEmailBtn.value = true;
                    sendEmail.value = false;
                    clearInterval(timer);
                }
            }, 60000);
            ElMessage({
                message: res.message,
                type: 'success',
                duration: 3000,
            });
        })
        .catch((_err) => {
            // 邮箱不可用
            errorEmailFormat.value = true;
            errorEmail.value = true;
            sendEmailBtn.value = false;
            sendEmail.value = false;
        });
};
// 验证邮箱验证码
const validateAuthCode = () => {
    const reg = new RegExp(/^[0-9]{4}$/);
    if (!reg.test(form.authCode.join(''))) {
        ElMessage({
            message: '请输入4位数字验证码。',
            type: 'error',
            duration: 3000,
        });
        return false;
    }

    return true;
};

/* ***********************************注册账号*********************************** */
// 注册事件
const registerEvent = async () => {
    if (validateUsername() && validatePassword() && validateAuthCode()) {
        const result = await useUser.register(form);
        if (result) {
            router.replace('/index');
        }
    } else {
        ElMessage({
            message: '请先填写完表单后，再注册。',
            type: 'warning',
            duration: 3000,
        });
    }
};
// 跳转登录
const goToLoginEvent = () => {
    router.push({ name: 'Login', query: { redirect: '/index' } });
};
</script>

<style scoped lang="scss">
.wrapper {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: auto;
}

// 表单
.form {
    --red: #e21e1e;
    --bg-light: #efefef;
    --bg-dark: #707070;
    --clr: #58bc82;
    --clr-alpha: #9c9c9c60;
    --ch-black: #141414;
    --ch-white: #e1e1e1;
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    width: 100%;
    max-width: 400px;

    // 表单子项
    .form-items {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        overflow: hidden;
        padding: 2px 2px;
        gap: 0.5rem;

        // input label
        .label {
            width: 100%;
            align-self: flex-start;
            color: var(--clr);
            font-weight: 600;
        }

        // input
        input[type='email'],
        input[type='password'],
        input[type='text'] {
            border-radius: 0.5rem;
            padding: 1rem 0.75rem;
            width: 80%;
            border: none;
            background-color: var(--clr-alpha);
            outline: 2px solid var(--bg-dark);
        }
        // input focus
        input[type='email']:focus,
        input[type='password']:focus,
        input[type='text']:focus {
            outline: 2px solid var(--clr);
        }

        // status
        .status {
            width: 20%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .error {
            color: var(--red);
        }

        .email-send-text {
            color: var(--clr);
            cursor: pointer;
        }
    }

    // 验证码
    .email-auth {
        display: flex;
        justify-content: space-between;
        gap: 25px;

        & input {
            height: 2.5em;
            width: 2.5em;
            outline: none;
            text-align: center;
            font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
            font-size: 1.5rem;
            color: var(--ch-black);
            border-radius: 5px;
            border: 2.5px solid var(--ch-white);
            background-color: var(--ch-white);
        }

        & input:focus {
            border: 1px solid var(--night-rider);
            box-shadow: inset 10px 10px 10px rgba(0, 0, 0, 0.15);
            transform: scale(1.05);
            transition: 0.5s;
        }
    }

    // 提交
    .submit {
        padding: 1rem 0.75rem;
        width: 100%;
        max-width: 320px;
        text-align: center;
        border-radius: 3rem;
        background-color: var(--bg-dark);
        color: var(--bg-light);
        border: none;
        cursor: pointer;
        transition: all 300ms;
        font-weight: 600;
        font-size: 0.9rem;

        &:hover {
            background-color: var(--clr);
            color: var(--bg-dark);
        }
    }

    // 底部文字
    .span {
        text-decoration: none;
        color: var(--bg-dark);
        & a {
            color: var(--clr);
        }
    }
}
</style>
